package com.sskj.level.ui.fragment;


import android.annotation.SuppressLint;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jakewharton.rxbinding2.widget.RxRadioGroup;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.base.App;
import com.sskj.common.box.inputfilter.MoneyValueFilter;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.depth.bean.DepthData;
import com.sskj.depth.bean.IDepthData;
import com.sskj.depth.view.DepthMapView;
import com.sskj.level.R;
import com.sskj.level.R2;
import com.sskj.level.bean.AssetListBean;
import com.sskj.level.bean.BuySellEnum;
import com.sskj.level.bean.CoinUpdateBean;
import com.sskj.level.bean.TradeInfoBean;
import com.sskj.level.component.DaggerUserDataComponent;
import com.sskj.level.presenter.BuyAndSellFragmentPresenter;
import com.sskj.level.util.TipLevelUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.LevelCoinType;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.bean.WSFiveBean;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.BottomSheetUtil;
import com.sskj.lib.util.CoinUtil;
import com.sskj.lib.util.CommonUtil;
import com.sskj.lib.util.NumberUtil;
import com.sskj.lib.util.TipUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;

/**
 * 合约交易买卖
 */
@SuppressLint("SetTextI18n")
@Route(path = RConfig.LEVEL_FRAGMENT_BUY_AND_SELL)
public class BuyAndSellFragment extends BaseFragment<BuyAndSellFragmentPresenter> {
    @BindView(R2.id.rbBuy)
    RadioButton rbBuy;
    @BindView(R2.id.rbSell)
    RadioButton rbSell;
    @BindView(R2.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R2.id.llPriceMode)
    LinearLayout llPriceMode;
    @BindView(R2.id.etPrice)
    EditText etPrice;
    @BindView(R2.id.tvDecrease)
    TextView tvDecrease;
    @BindView(R2.id.cuttingLine)
    TextView cuttingLine;
    @BindView(R2.id.tvIncrease)
    TextView tvIncrease;
    @BindView(R2.id.tvLevel)
    TextView tvLevel;
    @BindView(R2.id.llAddAndDe)
    LinearLayout llAddAndDe;
    @BindView(R2.id.rlEditPrice)
    RelativeLayout rlEditPrice;
    @BindView(R2.id.llHidePrice)
    RelativeLayout llHidePrice;
    @BindView(R2.id.etNum)
    EditText etNum;
    @BindView(R2.id.tvMoney)
    TextView tvMoney;
    @BindView(R2.id.tvTradeMoney)
    TextView tvTradeMoney;
    @BindView(R2.id.btTrade)
    Button btTrade;
    @BindView(R2.id.tvPrice)
    TextView tvPrice;
    @BindView(R2.id.tvMarketLimit)
    TextView tvMarketLimit;
    @BindView(R2.id.tvCoinType)
    TextView tvCoinType;
    @BindView(R2.id.frameLayoutFive)
    FrameLayout frameLayoutFive;
    @BindView(R2.id.rgPager)
    RadioGroup rgPager;
    @BindView(R2.id.rb25)
    RadioButton rb25;
    @BindView(R2.id.rb50)
    RadioButton rb50;
    @BindView(R2.id.rb75)
    RadioButton rb75;
    @BindView(R2.id.rb100)
    RadioButton rb100;
    @BindView(R2.id.llBoomRate)
    LinearLayout llBoomRate;
    @BindView(R2.id.llLevelMode)
    LinearLayout llLevelMode;
    @BindView(R2.id.depthMapView)
    DepthMapView depthMapView;
    private int pager = 1;
    @Autowired(required = true)
    String code = "BTC/USDT";//币种类型code
    String type = "BTC";//币种类型
    private boolean isBuy = true;
    private boolean isMarketPrice = true;  // 市价限价  （默认限价）
    private String marketPrice = "5000";//市价
    private String currentPrice = "5000";//限价
    private String usdtMoney = "0";//可用USDT
    private String maxTradeCoin = "10";//最大可交易币种数量
    private String minTradeCoin = "10";//最小可交易币种数量
    private String fee = "0.15";//手续费
    private int level = 20;//杠杆
    String[] levels = new String[]{
            "20", "50", "100"
    };
    private UserData userData;
    private String distancePrice = "0";
    private String sellPrice = "500";
    private String buyPrice = "500";

    private String orderPrice;
    private String transWare;
    private BottomSheetDialog levelPop;
    private MaterialDialog boomDialog;
    private String paperValue = "1";
    private BottomSheetDialog bottomSheetPrice;
    private String ensureMoney;//计算出的保证金
    private String usdtFull;
    private Disposable priceDispo;
    private Disposable numDispo;

    int[] pagers = new int[]{
            25, 50, 75, 100
    };
    BigDecimal feeBig;
    @Inject
    UserViewModel userViewModel;

    @Override
    protected int getLayoutId() {
        return R.layout.level_fragment_buy_sell;
    }

    @Override
    public BuyAndSellFragmentPresenter getPresenter() {
        return new BuyAndSellFragmentPresenter();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void initView() {
        DaggerUserDataComponent.create().inject(this);
        ARouter.getInstance().inject(this);
        initClick();
        depthMapView.setDrawText(false);
        etPrice.setFilters(new InputFilter[]{new MoneyValueFilter(CoinUtil.getPriceKeepNum(code))});
        etNum.setFilters(new InputFilter[]{new MoneyValueFilter(2)});
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                usdtMoney = "0";
            } else {
                userData = null;
                usdtMoney = "0";
                btTrade.setText(App.INSTANCE.getString(R.string.levelbuyAndSellFragment1));
            }
            type = code.split("/")[0].toUpperCase();
            mPresenter.getBalance(userData);
            mPresenter.getCoinInfo(code);
            updateUI();
        });
        LiveDataBus.get().with(RxBusCode.CHANGE_PRICE, String.class)
                .observe(this, s -> {
                    if (!isMarketPrice) {
                        etPrice.setText(CoinUtil.keepCoinPrice(code, s));
                        etPrice.setSelection(etPrice.getText().toString().length());

                    }
                });
        getChildFragmentManager()
                .beginTransaction()
                .add(R.id.frameLayoutFive, (Fragment) ARouter.getInstance()
                        .build(RConfig.LEVEL_FRAGMENT_FIVE)
                        .withString(Constans.CODE, code)
                        .navigation()
                ).commitAllowingStateLoss();
    }

    @Override
    public void initData() {
        userViewModel.update();
        LiveDataBus.get().with(RxBusCode.LEVEL_FRESH)
                .observe(this, o -> refresh());
        LiveDataBus.get().with(RxBusCode.PUSH_LEVEL_COIN_TYPE, LevelCoinType.class)
                .observe(this, this::refresh);
        LiveDataBus.get().with(RxBusCode.PUSH_COIN_BEAN, CoinBean.class)
                .observe(this, this::updateCoin);
        LevelCoinType coinType = new LevelCoinType(code);
        coinType.setBuy(true);
        refresh(coinType);

    }


    public void refresh(LevelCoinType coinType) {
        isBuy = coinType.isBuy();
        isMarketPrice = true;
        code = coinType.getCode().toLowerCase();
        type = coinType.getCode().split("/")[0].toUpperCase();
        tvCoinType.setText(type);
        etPrice.setFilters(new InputFilter[]{new MoneyValueFilter(CoinUtil.getPriceKeepNum(code))});
        mPresenter.initSocket(code);
        refresh();
    }

    /**
     * 刷新页面
     */
    public void refresh() {
        mPresenter.getCoinInfo(code);
        mPresenter.getBalance(userData);
        mPresenter.getDeepData(code);
        //刷新时，恢复一些默认属性
        isMarketPrice = true;
        isBuy = true;
        rgPager.clearCheck();
        etNum.setText("");
        etNum.clearFocus();
    }

    public void updateCoin(CoinBean stock) {
        if (stock.getCode().equalsIgnoreCase(code.toUpperCase()) && getActivity() != null) {
            marketPrice = stock.getPrice();
            buyPrice = stock.getBuy();
            sellPrice = stock.getSell();
            tvPrice.setText(marketPrice);
            if (isMarketPrice) {
                calculateMaxTrade();
                changeShowData();
            }
        }
    }


    public void updateCoinData(CoinUpdateBean coinUpdateBean) {
        sellPrice = coinUpdateBean.getSellPrice();
        buyPrice = coinUpdateBean.getBuyPrice();
        marketPrice = coinUpdateBean.getPrice();
        levels = coinUpdateBean.getLevels().split(",");
        level = Double.valueOf(levels[0]).intValue();
        distancePrice = new BigDecimal(coinUpdateBean.getSpread()).multiply(new BigDecimal(coinUpdateBean.getSlidingScalePrice())).toPlainString();
        minTradeCoin = coinUpdateBean.getMinDealNum();
        type = code.replace("_", "/").split("/")[0].toUpperCase();
        fee = new BigDecimal(coinUpdateBean.getShouPer()).multiply(new BigDecimal("0.01")).toPlainString();
        etPrice.setText(marketPrice);
        updateLevelButton();
        updateUI();

    }

    /**
     * 动态更新杠杆按钮
     */
    private void updateLevelButton() {
        levelPop = BottomSheetUtil.getBottomSheet(getActivity(), null, (recyclerView, position, v) -> {
            levelPop.dismiss();
            level = Double.valueOf(levels[position]).intValue();
            updateUI();
        }, levels);

    }


    private void initClick() {
        RxRadioGroup.checkedChanges(radioGroup)
                .subscribe(clickId -> {
                    if (!isBuy && clickId == rbBuy.getId()) {//购买
                        isBuy = true;
                        updateUI();
                    } else if (isBuy && clickId == rbSell.getId()) {//出售
                        isBuy = false;
                        updateUI();
                    }

                });
        ClickUtil.click(llBoomRate, () -> {
            if (!TextUtils.isEmpty(transWare)) {
                boomDialog = TipUtil.getSureCancelTip(getActivity(), String.format(App.INSTANCE.getString(R.string.levelbuyAndSellFragment2), transWare), () -> {
                    boomDialog.dismiss();
                });
                boomDialog.show();
            }

        });
        ClickUtil.click(llLevelMode, () -> {
            if (levelPop != null) {
                levelPop.show();
            }
        });
        rgPager.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == -1)
                return;
            etNum.clearFocus();
            if (TextUtils.isEmpty(maxTradeCoin)) {
                etNum.setText("0");
                return;
            }
            pager = pagers[group.indexOfChild(group.findViewById(checkedId))];
            String s = new BigDecimal(maxTradeCoin).multiply(new BigDecimal(pager)).multiply(new BigDecimal(0.01)).toBigInteger() + "";
            etNum.setText(s);
            updateUI();
        });
        etNum.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                rgPager.clearCheck();
            }
        });

        ClickUtil.click(llPriceMode, () -> {
            if (bottomSheetPrice == null) {
                bottomSheetPrice = BottomSheetUtil.getBottomSheet(getActivity(), null, new ItemClickSupport.OnItemClickListener() {
                    @Override
                    public void onItemClicked(RecyclerView recyclerView, int i, View view) {
                        bottomSheetPrice.dismiss();
                        if (i == 1) {
                            tvMarketLimit.setText(App.INSTANCE.getString(R.string.levelbuyAndSellFragment3));
                            isMarketPrice = false;
                            updateUI();
                        } else if (i == 0) {
                            tvMarketLimit.setText(App.INSTANCE.getString(R.string.levelbuyAndSellFragment4));
                            isMarketPrice = true;
                            updateUI();
                        }
                    }
                }, App.INSTANCE.getString(R.string.levelbuyAndSellFragment3), App.INSTANCE.getString(R.string.levelbuyAndSellFragment4));
            }
            bottomSheetPrice.show();
        });


        ClickUtil.click(100, tvDecrease, () -> {
            if (TextUtils.isEmpty(etPrice.getText())) {
                currentPrice = "0";
            }
            double pow = Math.pow(0.1, CoinUtil.getPriceKeepNum(code));
            BigDecimal priceDecimal = new BigDecimal(currentPrice).subtract(new BigDecimal(pow));
            if (priceDecimal.doubleValue() <= 0) {
                etPrice.setText("0");
            } else {
                priceDecimal = priceDecimal.setScale(CoinUtil.getPriceKeepNum(code), RoundingMode.DOWN);
                etPrice.setText(priceDecimal.toPlainString());
            }
        });
        ClickUtil.click(100, tvIncrease, () -> {
            if (TextUtils.isEmpty(etPrice.getText())) {
                currentPrice = "0";
            }
            double pow = Math.pow(0.1, CoinUtil.getPriceKeepNum(code));

            BigDecimal priceDecimal = new BigDecimal(currentPrice).add(new BigDecimal(pow));
            priceDecimal = priceDecimal.setScale(CoinUtil.getPriceKeepNum(code), RoundingMode.DOWN);
            etPrice.setText(priceDecimal.toPlainString());
        });

        DisposUtil.close(priceDispo);

        priceDispo = RxTextView.afterTextChangeEvents(etPrice)
                .subscribe(value -> {
                    if (TextUtils.isEmpty(value.editable().toString())) {
                        currentPrice = "0";
                    } else {
                        currentPrice = value.editable().toString();
                    }
                    calculateMaxTrade();
                    changeShowData();
                }, e -> System.out.println(e));
        DisposUtil.close(numDispo);
        numDispo = RxTextView.afterTextChangeEvents(etNum)
                .subscribe(value -> {

                    if (TextUtils.isEmpty(value.editable()) || Double.valueOf(value.editable().toString()) == 0 ||
                            TextUtils.isEmpty(etPrice.getText()) || Double.valueOf(etPrice.getText().toString()) == 0) {
                    } else {
                        if (Double.valueOf(value.editable().toString()) > Double.valueOf(maxTradeCoin)) {
                            etNum.setText(maxTradeCoin);
                            ToastUtil.showShort(App.INSTANCE.getString(R.string.levelbuyAndSellFragment5));
                        }
                    }
                    changeShowData();
                });
    }

    /**
     * 更新界面根据
     * 买入卖出，市价限价，币种，可用金额 变化 初始化界面
     */
    @SuppressLint({"SetTextI18n", "CheckResult"})
    private void updateUI() {
        calculateMaxTrade();
        if (radioGroup == null)
            return;
        radioGroup.check(isBuy ? R.id.rbBuy : R.id.rbSell);
        tvMarketLimit.setText(isMarketPrice ? App.INSTANCE.getString(R.string.levelbuyAndSellFragment3) : App.INSTANCE.getString(R.string.levelbuyAndSellFragment4));
        rlEditPrice.setVisibility(isMarketPrice ? View.GONE : View.VISIBLE);
        llHidePrice.setVisibility(isMarketPrice ? View.VISIBLE : View.GONE);
        tvCoinType.setText(type);
        tvLevel.setText(level + "");
        if (isBuy) {
            etPrice.setText(sellPrice);
        } else {
            etPrice.setText(buyPrice);
        }
        tvPrice.setText(marketPrice);

        DisposUtil.close(priceDispo);
        priceDispo = RxTextView.afterTextChangeEvents(etPrice)
                .subscribe(value -> {
                    if (TextUtils.isEmpty(value.editable().toString())) {
                        currentPrice = "0";
                    } else {
                        currentPrice = value.editable().toString();
                    }
                    calculateMaxTrade();
                    changeShowData();
                }, e -> System.out.println(e));
//        etNum.setText("");
        etNum.setHint(App.INSTANCE.getString(R.string.levelbuyAndSellFragment6) + minTradeCoin);

        tvMoney.setText(CoinUtil.keepUSDT(usdtMoney) + "USDT");

        btTrade.setBackground(ContextCompat.getDrawable(App.INSTANCE, isBuy ? R.drawable.level_shape_green : R.drawable.level_shape_red));
        if (userData != null) {
            btTrade.setText(isBuy ? BuySellEnum.BUY.getTitle() : BuySellEnum.SELL.getTitle());
            ClickUtil.click(btTrade, () -> {
                if (checkParam()) {
                    createOrder();
                }
            });
        } else {
            btTrade.setText(App.INSTANCE.getString(R.string.levelbuyAndSellFragment1));
            ClickUtil.click(btTrade, () -> {
                ARouter.getInstance().build(RConfig.LOGIN_LOGIN).navigation();
                getActivity().overridePendingTransition(R.anim.lib_anim_in, R.anim.lib_anim_out);

            });
        }
        changeShowData();
    }

    /**
     * 计算最大可输入数量
     */
    private void calculateMaxTrade() {
        if (isMarketPrice) {
            currentPrice = marketPrice;
        } else {
            currentPrice = etPrice.getText().toString();
        }
        if (TextUtils.isEmpty(currentPrice) || Double.valueOf(currentPrice) == 0) {
            maxTradeCoin = "0";
        } else {
//            if (isMarketPrice) {
//                BigDecimal marketDistancePriceDig;
//                if (isBuy) {
//                    marketDistancePriceDig = new BigDecimal(marketPrice).add(new BigDecimal(distancePrice));
//                } else {
//                    marketDistancePriceDig = new BigDecimal(marketPrice).subtract(new BigDecimal(distancePrice));
//                }
//                if (marketDistancePriceDig.doubleValue() <= 0) {
//                    marketDistancePriceDig = new BigDecimal("1");
//                }
//                maxTradeCoin = new BigDecimal(usdtMoney).divide(new BigDecimal("1").divide(new BigDecimal(level), 8, BigDecimal.ROUND_HALF_DOWN).add(new BigDecimal(fee)).multiply(marketDistancePriceDig), 8, BigDecimal.ROUND_HALF_UP).toPlainString() + "";
//            } else {
//                maxTradeCoin = new BigDecimal(usdtMoney).divide(new BigDecimal("1").divide(new BigDecimal(level), 8, BigDecimal.ROUND_HALF_DOWN).add(new BigDecimal(fee)).multiply(new BigDecimal(currentPrice)), 8, BigDecimal.ROUND_HALF_UP).toPlainString() + "";
//            }
//            maxTradeCoin = new BigDecimal(maxTradeCoin).divide(new BigDecimal(paperValue), 0, BigDecimal.ROUND_DOWN).toPlainString() + "";

            BigDecimal marketDistancePriceDig;
            if (isBuy) {
                marketDistancePriceDig = new BigDecimal(currentPrice).add(new BigDecimal(distancePrice));
            } else {
                marketDistancePriceDig = new BigDecimal(currentPrice).subtract(new BigDecimal(distancePrice));
            }
            if (marketDistancePriceDig.doubleValue() <= 0) {
                marketDistancePriceDig = new BigDecimal("1");
            }
            maxTradeCoin = new BigDecimal(usdtMoney).divide(new BigDecimal("1").divide(new BigDecimal(level), 8, BigDecimal.ROUND_HALF_DOWN).add(new BigDecimal(fee)).multiply(marketDistancePriceDig), 8, BigDecimal.ROUND_HALF_UP).toPlainString() + "";
//            }
            maxTradeCoin = new BigDecimal(maxTradeCoin).divide(new BigDecimal(paperValue), 0, BigDecimal.ROUND_DOWN).toPlainString() + "";

        }
        if (Double.valueOf(maxTradeCoin) <= 0) {
            maxTradeCoin = "0";
        }
    }

    /**
     * 检测购买条件
     *
     * @return
     */
    private boolean checkParam() {
        if (userData == null) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.levelbuyAndSellFragment7));
            return false;
        }
        if (!isMarketPrice) {
            if (TextUtils.isEmpty(etPrice.getText()) || Double.valueOf(etPrice.getText().toString()) == 0) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.levelbuyAndSellFragment8));
                return false;
            }
        }
        if (TextUtils.isEmpty(etNum.getText()) || Double.valueOf(etNum.getText().toString()) == 0) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.levelbuyAndSellFragment9));
            return false;
        }
        if (Double.valueOf(etNum.getText().toString()) < Double.valueOf(minTradeCoin)) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.levelbuyAndSellFragment10) + minTradeCoin);
            return false;
        }

        return true;
    }

    /**
     * 根据
     * 价格，数量，滑竿更新交易额
     * 价格*数量*（1+手续费）/杠杆
     */
    private void changeShowData() {

        String orderPrice;
        BigDecimal numBig;
        usdtFull = "0";
        ensureMoney = "0";
        feeBig = new BigDecimal("0");
        tvTradeMoney.setText("0");
        if (isMarketPrice) {//市价 购买加点差 出售减点差
            if (TextUtils.isEmpty(marketPrice) || TextUtils.isEmpty(etNum.getText())) {
                return;
            } else {
                numBig = new BigDecimal(etNum.getText().toString()).multiply(new BigDecimal(paperValue));
                if (isBuy) {
                    orderPrice = new BigDecimal(marketPrice).add(new BigDecimal(distancePrice)).toPlainString();
                } else {
                    orderPrice = new BigDecimal(marketPrice).subtract(new BigDecimal(distancePrice)).toPlainString();
                }

            }
        } else {//限价
            if (TextUtils.isEmpty(etPrice.getText()) || TextUtils.isEmpty(etNum.getText())) {
                return;
            } else {
                numBig = new BigDecimal(etNum.getText().toString()).multiply(new BigDecimal(paperValue));
//                orderPrice = marketPrice;
                if (isBuy) {
                    orderPrice = new BigDecimal(etPrice.getText().toString()).add(new BigDecimal(distancePrice)).toPlainString();
                } else {
                    orderPrice = new BigDecimal(etPrice.getText().toString()).subtract(new BigDecimal(distancePrice)).toPlainString();
                }
            }
        }
        usdtFull = new BigDecimal(orderPrice).multiply(numBig).divide(new BigDecimal(level), 8, RoundingMode.HALF_UP).toPlainString();
        ensureMoney = CoinUtil.keepUSDT(usdtFull);
        feeBig = new BigDecimal(orderPrice).multiply(numBig).multiply(new BigDecimal(fee));
        usdtFull = new BigDecimal(usdtFull).add(feeBig).toPlainString();
        tvTradeMoney.setText(CoinUtil.keepUSDT(usdtFull));
    }

    public void buySuccess() {
        userViewModel.update();
        LiveDataBus.get().with(RxBusCode.LEVEL_FRESH).postValue(1);
        ARouter.getInstance().build(RConfig.LEVEL_TRADE).withString(Constans.CODE, code).navigation();
    }


    /**
     * 计算下单后的爆仓率及提醒
     * 动态权益=当前持仓保证金+可用余额+浮动盈亏
     * 爆仓率=动态权益/当前持仓保证金
     *
     * @param data
     */
    public void updateRisk(TradeInfoBean data) {
        usdtMoney = data.getUsableFund();
        transWare = data.getBlowingUprate();
        updateUI();
    }

    /**
     * 下单
     */
    private void createOrder() {

        if (isBuy) {
            orderPrice = new BigDecimal(isMarketPrice ? marketPrice : etPrice.getText().toString()).add(new BigDecimal(distancePrice)).toPlainString();

        } else {
            orderPrice = new BigDecimal(isMarketPrice ? marketPrice : etPrice.getText().toString()).subtract(new BigDecimal(distancePrice)).toPlainString();
        }

        orderPrice = CoinUtil.keepCoinPrice(code, orderPrice);

        //做多或做空弹出框
        TipLevelUtil.showTradeInfo(getActivity(),

                isBuy ? BuySellEnum.BUY.getTitle() : BuySellEnum.SELL.getTitle(),
                isMarketPrice ? App.INSTANCE.getString(R.string.levelbuyAndSellFragment11) : App.INSTANCE.getString(R.string.levelbuyAndSellFragment12),
                orderPrice,
                etNum.getText().toString(),
                tvTradeMoney.getText().toString(),
                CoinUtil.keepUSDT(String.valueOf(feeBig))
                ,ensureMoney
                , String.valueOf(level), () ->
                        mPresenter.createOrder(
                                etNum.getText().toString(),
                                orderPrice,
                                code,
                                isMarketPrice ? "1" : "2",
                                isBuy ? BuySellEnum.BUY.getType() : BuySellEnum.SELL.getType(),
                                "0",
                                "0",
                                level + ""));
    }

    @Override
    public void onDestroy() {
        DisposUtil.close(numDispo);
        DisposUtil.close(priceDispo);
        super.onDestroy();
    }

    public void updateDeep(WSFiveBean data) {
        Collections.reverse(data.getAsks());
        Collections.reverse(data.getBids());
        Flowable<List<IDepthData>> buyFlow = Flowable.fromIterable(data.getBids())
                .map(fiveBean -> (IDepthData) new DepthData(fiveBean.getDoubleTotalSize(), fiveBean.getPrice()))
                .toList()
                .toFlowable();
        Flowable<List<IDepthData>> sellFlow = Flowable.fromIterable(data.getAsks())
                .map(fiveBean -> (IDepthData) new DepthData(fiveBean.getDoubleTotalSize(), fiveBean.getPrice()))
                .toList()
                .toFlowable();

        Flowable.zip(buyFlow, sellFlow, (buyData, sellData) -> {
            if (depthMapView != null) {
                depthMapView.setData(buyData, sellData);
            }
            return "1";
        }).subscribe();
    }
}
